import {
  createEvent,
  deleteEventById,
  getEventDetail,
  getEventList,
  getEventLogs,
  updateAtta,
  updateEvent,
} from '@/api/event';
import { create, deleteById, getList, update } from '@/api/manager';
import { DATE_FORMAT, eventMap, eventOptions } from '@/utils';
import { getName } from '@/utils/cache';
import { ArrowRightOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Cascader,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select,
  Table,
  Upload,
  message,
} from 'antd';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import React, { useState } from 'react';
import { cityDataForLabel } from '../../utils/area';

export default () => {
  const [createModalVis, setCreateModalVis] = useState(false);
  const [infoModalVis, setInfoModalVis] = useState(false);
  const [infoModalVis2, setInfoModalVis2] = useState(false);
  const [data, setData] = useState([]);
  const [eventData, setEventData] = useState([]);
  const [editRow, setEditRow] = useState(null);
  const [editEventRow, setEditEventRow] = useState(null);
  const [avatarUrl, setAvatarUrl] = useState(null);
  const [eventLogs, setEventLogs] = useState([]);
  const [attachments, setAttachments] = useState([]);

  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [eventForm] = Form.useForm();
  const [searchForm] = Form.useForm();

  const initAttachements = async (id) => {
    const resp = await getEventDetail({ id });
    console.log('😈resp', resp);
    const attachments = resp?.data?.attachments;
    setAttachments(attachments);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '个人照片',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (_) =>
        !_ ? (
          '暂无'
        ) : (
          <img
            src={_}
            alt=""
            style={{ width: '50px', height: '50px', objectFit: 'contain', borderRadius: 6 }}
          />
        ),
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '区划',
      dataIndex: 'area',
      key: 'area',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '任职单位',
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '项目单位',
      dataIndex: 'project_company_name',
      key: 'project_company_name',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_, record) => {
        return (
          <div className="flex-aic">
            <Button
              type="primary"
              onClick={() => {
                const row = cloneDeep(record);
                if (row.birthday) row.birthday = dayjs(record.birthday).add(8, 'hours');
                setEditRow(row);
                editForm.setFieldsValue(row);
                setInfoModalVis(true);
                initEvent(row.id);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              description="确认删除？"
              onConfirm={async () => {
                const resp = await deleteById(record.id);
                if (resp.code === 0) {
                  message.success('删除成功');
                  init();
                } else {
                  message.error('删除失败');
                }
              }}
            >
              <Button danger type="primary" className="ml10">
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const columns2 = [
    {
      title: '时间',
      dataIndex: 'time',
      width: 200,
      key: 'time',
      render: (_) => {
        if (_) return dayjs(_).format('YYYY-MM-DD');
        return '暂无';
      },
    },
    {
      title: '事项类型',
      width: 150,
      dataIndex: 'type',
      key: 'type',
      render: (_) => {
        if (_) return eventMap[_];
        return '暂无';
      },
    },
    {
      title: '项目单位',
      dataIndex: 'project_company_name',
      key: 'project_company_name',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (_) => {
        if (_) return _;
        return '暂无';
      },
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    // {
    //   title: '操作人',
    //   dataIndex: 'oprator',
    //   key: 'oprator',
    // },
    {
      title: '操作',
      dataIndex: 'action',
      width: 150,
      key: 'action',
      render: (_, record) => {
        return (
          <div className="flex-aic">
            <Button
              type="primary"
              onClick={async () => {
                initAttachements(record.id);

                const _row = cloneDeep(record);
                _row.time = dayjs(_row.time);
                console.log('😈record.id', record.id);
                eventForm.resetFields();
                eventForm.setFieldsValue(_row);
                setEditEventRow(_row);
                setInfoModalVis2(true);

                const logResp = await getEventLogs({ event_id: record.id });
                setEventLogs(logResp?.data?.list);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              description="确认删除？"
              onConfirm={async () => {
                const resp = await deleteEventById(record.id);
                if (resp.code === 0) {
                  message.success('删除成功');
                  initEvent();
                } else {
                  message.error('删除失败');
                }
              }}
            >
              <Button danger type="primary" className="ml10">
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const columns3 = [
    {
      title: '时间',
      dataIndex: 'created_time',
      key: 'created_time',
      width: 180,
      render: (_) => {
        if (_) return dayjs(_).format(DATE_FORMAT);
        return '暂无';
      },
    },
    {
      title: '操作人',
      width: 120,
      dataIndex: 'oprator',
      key: 'oprator',
    },
    {
      title: '操作内容',
      dataIndex: 'content',
      key: 'content',
      render: (_) => {
        try {
          const data = JSON.parse(_);
          const isSame =
            data?.before?.time === data?.after?.time &&
            data?.before?.type === data?.after?.type &&
            data?.before?.project_company_name === data?.after?.project_company_name &&
            data?.before?.project_name === data?.after?.project_name &&
            data?.before?.desc === data?.after?.desc;
          return (
            <div>
              {data.content}
              {isSame && <span>（无任何修改）</span>}
              {!isSame && (
                <div
                  className="flex mt10"
                  style={{ gap: 10, alignItems: 'center', justifyContent: 'space-between' }}
                >
                  {data?.before && (
                    <Card className="flex-1">
                      {data?.before.time !== data?.after.time && (
                        <h4>事项时间：{dayjs(data?.before.time).format('YYYY-MM-DD')}</h4>
                      )}
                      {data?.before.type !== data?.after.type && (
                        <h4>事项类型：{eventMap[data?.before.type]}</h4>
                      )}
                      {data?.before.project_company_name !== data?.after.project_company_name && (
                        <h4>项目单位：{data?.before.project_company_name}</h4>
                      )}
                      {data?.before.project_name !== data?.after.project_name && (
                        <h4>项目名称：{data?.before.project_name}</h4>
                      )}
                      {data?.before.desc !== data?.after.desc && <h4>描述：{data?.before.desc}</h4>}
                    </Card>
                  )}
                  {data?.before && <ArrowRightOutlined></ArrowRightOutlined>}
                  {data?.after && (
                    <Card className="flex-1">
                      {data?.before.time !== data?.after.time && (
                        <h4>事项时间：{dayjs(data?.after.time).format('YYYY-MM-DD')}</h4>
                      )}
                      {data?.before.type !== data?.after.type && (
                        <h4>事项类型：{eventMap[data?.after.type]}</h4>
                      )}
                      {data?.before.project_company_name !== data?.after.project_company_name && (
                        <h4>项目单位：{data?.after.project_company_name}</h4>
                      )}
                      {data?.before.project_name !== data?.after.project_name && (
                        <h4>项目名称：{data?.after.project_name}</h4>
                      )}
                      {data?.before.desc !== data?.after.desc && <h4>描述：{data?.after.desc}</h4>}
                    </Card>
                  )}
                </div>
              )}
            </div>
          );
        } catch {
          return '暂无日志';
        }
      },
    },
  ];

  const handleCreate = () => {
    console.log('😈create');
    createForm.validateFields().then(async (values) => {
      console.log('values', values);
      const params = cloneDeep(values);
      if (params.area) params.area = params.area?.join(',');
      if (params.birthday) params.birthday = dayjs(params.birthday).format('YYYY-MM-DD');

      const resp = await create({ ...params, avatar: avatarUrl });
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success('添加成功');
        init();
        setCreateModalVis(false);
        createForm.resetFields();
        setAvatarUrl(null);
      } else {
        message.error('添加失败，请重试');
      }
    });
  };

  const handleUpdate = () => {
    console.log('😈create');
    editForm.validateFields().then(async (values) => {
      console.log('values', values);
      if (values.area instanceof Array) values.area = values.area?.join(',');
      if (values.birthday) values.birthday = dayjs(values.birthday).format('YYYY-MM-DD');
      const resp = await update({ id: editRow.id, ...values });
      console.log('😈resp', resp);
      if (resp.code === 0) {
        message.success('编辑成功');
        init();
        setInfoModalVis(false);
        editForm.resetFields();
      } else {
        message.error('编辑失败，请重试');
      }
    });
  };

  const handleResolveEvent = () => {
    console.log('😈create');
    if (!editEventRow?.id) {
      eventForm.validateFields().then(async (values) => {
        if (values.time) values.time = dayjs(values.time).format('YYYY-MM-DD');

        const resp = await createEvent({
          ...values,
          manager_id: editRow.id,
          oprator: getName(),
          created_time: dayjs().format('YYYY-MM-DD hh:mm:ss'),
        });
        console.log('😈resp', resp);
        if (resp.code === 0) {
          message.success('新增成功');
          setInfoModalVis2(false);
          initEvent();
          eventForm.resetFields();
          setEditEventRow(null);
        } else {
          message.error('新增失败，请重试');
        }
      });
    } else {
      eventForm.validateFields().then(async (values) => {
        if (values.time) values.time = dayjs(values.time).format('YYYY-MM-DD');

        const resp = await updateEvent({ ...values, id: editEventRow.id, oprator: getName() });
        console.log('😈resp', resp);
        if (resp.code === 0) {
          message.success('编辑成功');
          setInfoModalVis2(false);
          initEvent();
          eventForm.resetFields();
          setEditEventRow(null);
        } else {
          message.error('编辑失败，请重试');
        }
      });
    }
  };

  const init = async () => {
    const searchVals = searchForm.getFieldsValue() || {};
    console.log('😈searchVals', searchVals);
    const resp = await getList(searchVals);
    console.log('😈resp', resp);
    let { list } = resp?.data || {};
    console.log('😈list', list);
    list = list?.map((item) => {
      if (item.area) {
        item.area = item.area?.split(',');
      }

      return item;
    });
    console.log('😈list', list);
    setData(list);
  };

  const initEvent = async (id) => {
    const resp = await getEventList({
      manager_id: id || editRow.id,
    });
    console.log('😈resp', resp);
    let { list } = resp?.data;
    console.log('😈list', list);
    setEventData(list);
  };

  React.useEffect(() => {
    init();
  }, []);
  console.log('😈editEventRow', editEventRow);
  return (
    <PageContainer>
      <Modal
        width={1100}
        open={createModalVis}
        title="项目经理信息新增"
        onCancel={() => setCreateModalVis(false)}
        onOk={handleCreate}
      >
        <Form layout="horizontal" form={createForm} labelCol={{ span: 5 }}>
          <Card title="个人信息">
            <Row gutter={[30, 10]}>
              <Col span={16}>
                <Row gutter={[10, 10]}>
                  <Col span={12}>
                    <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="性别" name="sex" rules={[{ required: true }]}>
                      <Select>
                        <Select.Option value="男">男</Select.Option>
                        <Select.Option value="女">女</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="出生年月" name="birthday">
                      <DatePicker style={{ width: '100%' }}></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="任职单位" name="company_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="项目单位" name="project_company_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="项目名称" name="project_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="区划" name="area">
                      {/* <Input></Input> */}
                      <Cascader
                        options={cityDataForLabel}
                        placeholder="请选择"
                        onChange={(e) => {
                          console.log('😈e', e);
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="成绩" name="score">
                      <Select>
                        <Select.Option value="优秀">优秀</Select.Option>
                        <Select.Option value="良好">良好</Select.Option>
                        <Select.Option value="不及格">不及格</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col span={8}>
                <Form.Item label="个人照片" name="avatar">
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={'http://47.120.50.132:16065/attachment/upload'}
                    accept="image/jpg,image/jpeg,image/png"
                    // action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
                    // beforeUpload={beforeUpload}
                    onChange={(e) => {
                      console.log('onChange', e);
                      if (e?.file?.response) {
                        console.log('😈e?.file?.response', e?.file?.response);
                        const path = e?.file?.response?.data?.path;
                        setAvatarUrl(path);
                      }
                    }}
                  >
                    {avatarUrl ? (
                      <img
                        src={avatarUrl}
                        alt=""
                        style={{ width: '150px', height: '150px', objectFit: 'contain' }}
                      />
                    ) : (
                      <button style={{ border: 0, background: 'none' }} type="button">
                        <PlusOutlined />
                        <div style={{ marginTop: 8 }}>上传</div>
                      </button>
                    )}
                  </Upload>
                </Form.Item>
              </Col>
            </Row>
          </Card>
        </Form>
      </Modal>

      <Modal
        width={1000}
        open={infoModalVis}
        title="项目经理信息编辑"
        onCancel={() => setInfoModalVis(false)}
        onOk={handleUpdate}
      >
        <Form layout="horizontal" form={editForm} initialValues={editRow} labelCol={{ span: 5 }}>
          <Card title="个人信息">
            <Row gutter={[30, 10]}>
              <Col span={16}>
                <Row gutter={[10, 10]}>
                  <Col span={12}>
                    <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="性别" name="sex" rules={[{ required: true }]}>
                      <Select>
                        <Select.Option value="男">男</Select.Option>
                        <Select.Option value="女">女</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="出生年月" name="birthday">
                      <DatePicker style={{ width: '100%' }}></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="任职单位" name="company_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="项目单位" name="project_company_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="项目名称" name="project_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="区划" name="area">
                      {/* <Input></Input> */}
                      <Cascader
                        options={cityDataForLabel}
                        placeholder="请选择"
                        onChange={(e) => {
                          console.log('😈e', e);
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="成绩" name="score">
                      <Select>
                        <Select.Option value="优秀">优秀</Select.Option>
                        <Select.Option value="良好">良好</Select.Option>
                        <Select.Option value="不及格">不及格</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col span={8}>
                <Form.Item label="个人照片" name="avatar">
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={'http://47.120.50.132:16065/attachment/upload'}
                    accept="image/jpg,image/jpeg,image/png"
                    // action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
                    // beforeUpload={beforeUpload}
                    onChange={(e) => {
                      console.log('onChange', e);
                      if (e?.file?.response) {
                        console.log('😈e?.file?.response', e?.file?.response);
                        const path = e?.file?.response?.data?.path;
                        setAvatarUrl(path);
                        setEditRow({
                          ...editRow,
                          avatar: path,
                        });
                        editForm.setFieldValue('avatar', path);
                      }
                    }}
                  >
                    {editRow?.avatar ? (
                      <img
                        src={editRow?.avatar}
                        alt=""
                        style={{ width: '150px', height: '150px', objectFit: 'contain' }}
                      />
                    ) : (
                      <button style={{ border: 0, background: 'none' }} type="button">
                        <PlusOutlined />
                        <div style={{ marginTop: 8 }}>上传</div>
                      </button>
                    )}
                  </Upload>
                </Form.Item>
              </Col>
            </Row>
          </Card>
          <Card title="信用信息" className="mt10">
            <div className="flex-bt mb10">
              <div></div>
              <Button
                type="primary"
                onClick={() => {
                  setInfoModalVis2(true);
                  setTimeout(() => {
                    setEditEventRow(null);
                    eventForm.resetFields();
                    eventForm.setFieldsValue({});
                  }, 200);
                }}
              >
                新增
              </Button>
            </div>
            <Table columns={columns2} dataSource={eventData}></Table>
          </Card>
        </Form>
      </Modal>

      <Modal
        width={1000}
        // open
        open={infoModalVis2}
        title="信用事项记录操作"
        onOk={handleResolveEvent}
        onCancel={() => {
          setTimeout(() => {
            setEditEventRow(null);
            eventForm.resetFields();
            eventForm.setFieldsValue({});
          });

          setInfoModalVis2(false);
        }}
      >
        <Form
          layout="horizontal"
          labelCol={{ span: 6 }}
          form={eventForm}
          initialValues={editEventRow || undefined}
        >
          <Card title="事项明细">
            <Row gutter={[30, 10]}>
              <Col span={24}>
                <Row gutter={[10, 10]}>
                  <Col span={12}>
                    <Form.Item label="事项时间" rules={[{ required: true }]} name="time">
                      <DatePicker className="w100" required></DatePicker>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="事项类型" rules={[{ required: true }]} name="type">
                      <Select options={eventOptions}></Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="项目单位"
                      rules={[{ required: true }]}
                      name="project_company_name"
                    >
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="项目名称" rules={[{ required: true }]} name="project_name">
                      <Input></Input>
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      name={'desc'}
                      rules={[{ required: true }]}
                      label="描述"
                      labelCol={{
                        span: 3,
                      }}
                    >
                      <Input.TextArea rows={5}></Input.TextArea>
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
            </Row>
          </Card>
          <Card
            title="相关附件"
            className="mt10"
            extra={
              <Upload
                action="http://47.120.50.132:16065/attachment/upload"
                // action="http://127.0.0.1:7001/attachment/upload"
                // listType="picture"
                showUploadList={false}
                onChange={async (e) => {
                  console.log('onChange', e);
                  if (e?.file?.response) {
                    const id = e?.file?.response?.data.id;
                    const resp = await updateAtta({
                      id,
                      event_id: editEventRow.id,
                    });
                    console.log('😈resp', resp);
                    if (resp.code === 0) {
                      message.success('上传成功');
                      console.log('😈上传成功', resp);
                      initAttachements(editEventRow.id);
                    }
                  }
                }}
                maxCount={5}
                multiple
                disabled={!editEventRow?.id}
              >
                <Button icon={<UploadOutlined />} disabled={!editEventRow?.id}>
                  {editEventRow?.id ? '上传' : '请新增后再进行上传'}
                </Button>
              </Upload>
            }
          >
            {editEventRow?.id && (
              <Row gutter={[10, 10]}>
                {attachments &&
                  attachments.map((item, index) => {
                    return (
                      <Col span={24} key={item.id}>
                        {/* <Card title={`附件 - ${index + 1}`}> */}
                        <a href={item.path} target="_blank" rel="noreferrer">
                          {item.name}
                        </a>
                        {/* </Card> */}
                      </Col>
                    );
                  })}
              </Row>
            )}
          </Card>
          {editEventRow?.id && (
            <Card title="编辑日志" className="mt10">
              <Table columns={columns3} dataSource={eventLogs} pagination={{ pageSize: 5 }}></Table>
            </Card>
          )}
        </Form>
      </Modal>

      <div className="flex-bt">
        <div className="flex-aic">
          <Form form={searchForm}>
            <Form.Item name="name" noStyle>
              <Input placeholder="请输入姓名" style={{ width: '200px' }}></Input>
            </Form.Item>
            <Form.Item name="company_name" noStyle>
              <Input
                placeholder="请输入任职单位"
                style={{ width: '200px' }}
                className="ml10"
              ></Input>
            </Form.Item>
            <Form.Item name="project_name" noStyle>
              <Input
                placeholder="请输入项目名称"
                style={{ width: '200px' }}
                className="ml10"
              ></Input>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className="flex-bt mt10">
        <div></div>
        <div>
          <Button type="primary" onClick={init}>
            搜索
          </Button>
          <Button
            type="primary"
            className="ml10"
            onClick={() => {
              setCreateModalVis(true);
            }}
          >
            添加
          </Button>
          <Upload
            action={'http://47.120.50.132:16065/manager/import'}
            showUploadList={false}
            onChange={(e) => {
              if (e?.file?.response) {
                console.log('😈e?.file?.response', e?.file?.response);
                if (e?.file?.response?.code == 0) {
                  message.success('导入成功');
                  init();
                } else {
                  message.error('导入失败');
                }
              }
            }}
          >
            <Button type="primary" className="ml10">
              导入
            </Button>
            <Button
              type="primary"
              className="ml10"
              onClick={() => {
                window.open(
                  'http://47.120.50.132:16061/attachment/1719069256572__物业导入模板.xlsx',
                );
              }}
            >
              获取模板
            </Button>
          </Upload>
          {/* <Button type="primary" className="ml10">
            导出
          </Button> */}
        </div>
      </div>

      <Table className="mt10" columns={columns} dataSource={data}></Table>
    </PageContainer>
  );
};
